package com.maomao.maomaochong_i.dataBean;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

/**
 * Created by maomao on 2017/6/18.
 */

public class MySharePreference {
    // SharedPreferences 文件名
    public static final String FILE_NAME = "loginState";
    private Context maoContext;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    public MySharePreference(Context maoContext) {
        this.maoContext = maoContext;
        sharedPreferences = maoContext.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        //注册数据变化监听
        sharedPreferences.registerOnSharedPreferenceChangeListener(lister);
    }

    //创建数据变化监听实例
    private SharedPreferences.OnSharedPreferenceChangeListener lister
            = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            //自行添加内容
        }
    };

    public void setData(String key, String value){
        editor.putString(key, value);
        editor.apply();
    }

    public void setData(String key, int value){
        editor.putInt(key, value);
        editor.apply();
    }

    public void setData(String key, boolean value){
        editor.putBoolean(key, value);
        Boolean bn = editor.commit();
        if (bn){
            Toast.makeText(maoContext,"登录成功",Toast.LENGTH_SHORT).show();
        }
    }

    public String getData(String key, String value){
        return sharedPreferences.getString(key, value);
    }

    public int getData(String key, int value){
        return sharedPreferences.getInt(key, value);
    }

    public boolean getData(String key, boolean value){
        return sharedPreferences.getBoolean(key, value);
    }

    public void removeData(String key){
        editor.remove(key);
        editor.apply();
    }

    public void clear(){
        editor.clear();
    }

}
